package com.bitauto.i.commonUtils.test;

import java.lang.ref.PhantomReference;
import java.lang.ref.ReferenceQueue;
import java.lang.ref.SoftReference;
import java.lang.ref.WeakReference;
import java.util.HashMap;
import java.util.Map;

public class ReferenceTypes {

    public static void main(String[] args) {
        // 强引用 - 不会被回收
        Object strongRef = new Object();

        // 软引用 - 内存不足时回收
        SoftReference<Object> softRef = new SoftReference<>(new Object());

        // 弱引用 - GC时回收
        WeakReference<Object> weakRef = new WeakReference<>(new Object());

        // 虚引用 - 主要用于跟踪对象被回收的状态
        ReferenceQueue<Object> queue = new ReferenceQueue<>();
        PhantomReference<Object> phantomRef = new PhantomReference<>(new Object(), queue);

        System.out.println("Strong: " + strongRef);
        System.out.println("Soft: " + softRef.get());
        System.out.println("Weak: " + weakRef.get());
        System.out.println("Phantom: " + phantomRef.get());

        // 触发GC
        System.gc();
        System.out.println("After GC:");
        System.out.println("Strong: " + strongRef);
        System.out.println("Soft: " + softRef.get());
        System.out.println("Weak: " + weakRef.get());
        System.out.println("Phantom: " + phantomRef.get());

        //System.out.println(tableSizeFor(16));

        Map m=new HashMap<>(16,0.75f);
        System.out.println(m.size());

        ThreadLocal<String> local1 = new ThreadLocal<>();
        ThreadLocal<Integer> local2 = new ThreadLocal<>();

        local1.set("hello");
        local2.set(123);

        // ThreadLocalMap 中现在有两个键值对
        System.out.println(local1.get()); // hello
        System.out.println(local2.get()); // 123


    }

    static final int MAXIMUM_CAPACITY = 1 << 30;

    static final int tableSizeFor(int cap) {
        int n = cap - 1;
        n |= n >>> 1;
        n |= n >>> 2;
        n |= n >>> 4;
        n |= n >>> 8;
        n |= n >>> 16;
        return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
    }

}
